package com.cl.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cl.bean.Dept;
import com.cl.bean.Emp;
import com.cl.dao.DeptDao;
import com.cl.dao.EmpDao;
import com.cl.service.DeptService;
import com.cl.utils.PageBean;

@Service
@Transactional
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	private DeptDao deptDao;
	
	@Autowired
	private EmpDao empDao;
	
	@Override
	public void save(Dept dept) {
		deptDao.save(dept);
	}

	@Override
	public PageBean getPageBean(DetachedCriteria dc, int page, int limit) {
		int count = deptDao.getTotalCount(dc);
		PageBean pb = new PageBean(page, limit, count);
		List<Dept> list = deptDao.getPageList(dc, pb.getStart(), pb.getPageSize());
		pb.setData(list);
		return pb;
	}

	@Override
	public Dept findById(int p_id) {
		return deptDao.findById(p_id);
	}

	@Override
	public void update(Dept dept) {
		deptDao.update(dept);
	}

	@Override
	public int findByName(String p_name) {
		return deptDao.findByName("SELECT count(*) FROM Dept WHERE p_name=?", p_name);
	}

	@Override
	public void del(int p_id) {
		deptDao.updateByTis("UPDATE Dept SET p_is = '0' WHERE p_id=?",p_id);
		DetachedCriteria dc = DetachedCriteria.forClass(Emp.class);
		dc.add(Restrictions.eq("dept.p_id", p_id));
		List<Emp> listEmp = empDao.finByDetachedCriteria(dc);
		for (Emp emp : listEmp) {
			empDao.updateByTis("UPDATE Emp SET e_is = '0' WHERE e_id=?", emp.getE_id());
		}
	}

	@Override
	public void restore(int p_id) {
		deptDao.updateByTis("UPDATE Dept SET p_is = '1' WHERE p_id=?",p_id);
	}

	@Override
	public List<Dept> getAllName() {
		DetachedCriteria dc = DetachedCriteria.forClass(Dept.class);
		dc.add(Restrictions.eq("p_is", "1"));
		List<Dept> list = deptDao.finByDetachedCriteria(dc);
		return list;
	}
}
